import React from 'react';
import Router from 'next/router';
import { NavBar, Icon, Flex, Modal, Button, Carousel, Toast } from 'antd-mobile';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import { utilDecoding, utilFormateDate, utilClient } from '../../tools/utils';

import { getRequest } from '../../tools/requests';

import HeadC from '../../src/components/layout/head';
import FooterC from '../../src/components/layout/footer';

import './index.css';

export default class GoodsDetails extends React.Component {
  static async getInitialProps({query}) {
    let goodsItem = JSON.parse( utilDecoding(query.goodsItem) );
    return {
      title: 'coupon',
			description: '',
			links: '',
			ogImage: '',
      goodsItem,
    }
  }
  constructor(props) {
    super(props);
    this.state = {
      copyShow: false,
      copyText: '',
      goodsDetails: {
        rate_keywords: [],
        evaluates: [],
        images: ["../../static/images/moren.png"]
      },
      couponDetails: [],
      imgHeight: '300px',
      goodsItem: this.props.goodsItem,
      shareInfo: {},
      utilClientStatus: ''
    }
  }
  componentWillMount() {}
  componentDidMount() {
    this.setState({
      utilClientStatus: utilClient()
    })
  }
  async handleCopyCunpon() {
    this.setState({ copyShow: true })
    if (!this.state.shareInfo.tbk_pwd) {
      await this.getShareLink();
    }
    this.setState({ copyText: this.state.shareInfo.tbk_pwd });
  }
  async getShareLink() {
    let { item_id } = this.state.goodsItem;
    let result = await getRequest('coupon_link/', {proId: item_id, _: Date.parse(new Date())})
    this.state.shareInfo = result.data|| this.state.shareInfo;
  }
  async handleLinkShareUrl() {
    await this.getShareLink();
    let { coupon_click_url } = this.state.shareInfo;
    if (!coupon_click_url) {
      Toast.fail('服务开小差了，请稍后再试！', 1);
      return
    }
    location.href = coupon_click_url;

  }
  handleCloseKL() {
    Toast.info("口令复制成功！！", 0.8, null, false)
  }

  render() {
		const { title, description, links, ogImage } = this.props;
    const { goodsItem, utilClientStatus } = this.state;
    let couponPrice = goodsItem.zk_final_price && goodsItem.coupon_amount ? (parseFloat(goodsItem.zk_final_price) -parseFloat(goodsItem.coupon_amount)).toFixed(2) : parseFloat(goodsItem.zk_final_price).toFixed(2);
    let smallImages = goodsItem.small_images instanceof Array ? goodsItem.small_images : goodsItem.small_images.split("|");
    return (
      <div>
        <HeadC 
					title={title} 
					description={description}
					links={links}
					ogImage={ogImage}
				></HeadC>
        <NavBar
          mode="light"
          icon={<Icon type="left" />}
          onLeftClick={() => Router.back()}
          style={{color: '#fa4d47', zIndex: 999}}
          className="detail-nav-block"
        >
          商品详情
        </NavBar>
        <section className="con-pon-details">
        {/* {
          goodsItem.small_images ? (
            <Carousel
              autoplay={true}
              dots={false}
              infinite
            >
              {goodsItem.small_images.split("|").map((item) => (
                <a style={{display: 'inline-block', width: '100%', height: this.state.imgHeight}} key={item}>
                  <img
                    src={item}
                    alt=""
                    style={{ width: '100%', verticalAlign: 'top' }}
                    onLoad={() => {
                      window.dispatchEvent(new Event('resize'));
                      this.setState({ imgHeight: 'auto' })
                    }}
                  />
                </a>
              ))}
            </Carousel>
          ) : (
            <div>
              <img style={{width: "100%", height: "auto"}} src={goodsItem.pict_url} />
            </div>
          )
        } */}
          <div>
            <img style={{width: "100%"}} src={goodsItem.pict_url} />
          </div>
          <div className="cun-pon-d">
            <span>领劵立减 ¥{ goodsItem.coupon_amount || 0.00 }</span>
            <span className="shop-tip"> { goodsItem.user_type === '1' ? '天猫商品' : '淘宝商品' } </span>
          </div>
          <div className="cun-pon-block">
            <h3 className="goods-block__title">{ goodsItem.title }</h3>
          </div>
          <div className="tip-block">
            <Flex>
              <Flex.Item className="tp-left-block">
                <span className="tp-title">用劵后</span>
                <span className="tp-l-price">¥{ couponPrice }</span>

                <span className="tp-now tp-color">原价 </span>
                <span className="tp-color">¥{goodsItem.zk_final_price}</span>
              </Flex.Item>
              <Flex.Item style={{textAlign: 'right'}}>
                <span className="tp-color">月销量 </span>
                <span className="tp-color">{goodsItem.volume}</span>
              </Flex.Item>
            </Flex>
            <div className='date-block-detail'>
              <span>使用期限 </span>
              {
                goodsItem.coupon_start_time || goodsItem.coupon_end_time ? (
                  <span>{utilFormateDate(goodsItem.coupon_start_time)} ～ {utilFormateDate(goodsItem.coupon_end_time)}</span>
                ) : (
                  <span> 暂无限制 </span>
                )
              }
            </div>
          </div>
          <div className="cun-pon-store-info">
            <p className="font1 color-gray"> 店铺信息 </p>
            <div className="s-logo-titile">
              <img src={goodsItem.shopLogo ? goodsItem.shopLogo : '../../static/images/dianpu.png'} alt="店铺logo" />
              <span> { goodsItem.shop_title } </span>
            </div>
          </div>
          {
            smallImages.map((item) => (
              <div key={item}>
                <img
                  src={item}
                  alt=""
                  style={{ width: '100%'}}
                />
              </div>
            ))
          }
          <FooterC src="../../static/images/police.png" />
        </section>
        <footer className="cun-pon-footer">
          {
            utilClientStatus == 1 || utilClientStatus == 2 ? (
              <Flex>
                <Flex.Item className="right-block" onClick={this.handleCopyCunpon.bind(this)}>
                  <span> 立即领劵 </span>
                </Flex.Item>
              </Flex>
            ) : (
              <Flex>
                <Flex.Item className="left-block" onClick={this.handleLinkShareUrl.bind(this)}>
                  <a>
                    <span> 立即领劵 </span>   
                  </a>
                </Flex.Item>
                <Flex.Item className="right-block" onClick={this.handleCopyCunpon.bind(this)}>
                  <span> 获取口令 </span>
                </Flex.Item>
              </Flex>
            )
          }
        </footer>
        <Modal
          className="copy-block"
          visible={this.state.copyShow}
          transparent
          title="淘宝口令"
          maskClosable={true}
          closable={true}
          onClose={() => this.setState({copyShow: false})}
          afterClose={this.handleCloseKL.bind(this)}
        >
          <div>
            <div className="kou-dialog-content">
              <span> { this.state.copyText ? this.state.copyText : '正在加载中...' } </span>
            </div>
            <div className="kou-dialog-zhu">
              <span>注：若复制失败，请手动复制口令</span>
            </div>
            <div className="kou-introduce">
              <span> 使用说明：复制口令后打开淘宝APP，搜索口令即可领劵购买 </span>
            </div>
            <CopyToClipboard text={this.state.copyText} onCopy={() => this.setState({copyShow: false})}>
              <Button className="copy-btn">一键复制</Button>
            </CopyToClipboard>
          </div>
        </Modal>
      </div>
    )
  }
}